Move updater/installer specific methods out of DatabaseBase
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28
29 /**
30 * Database abstraction object
31 * @ingroup Database
32 */
33 abstract class DatabaseBase implements IDatabase, LoggerAwareInterface {
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES = 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX = 1500000;
40
41 /** How long before it is worth doing a dummy query to test the connection */
42 const PING_TTL = 1.0;
43 const PING_QUERY = 'SELECT 1 AS ping';
44
45 const TINY_WRITE_SEC = .010;
46 const SLOW_WRITE_SEC = .500;
47 const SMALL_WRITE_ROWS = 100;
48
49 /** @var string SQL query */
50 protected $mLastQuery = '';
51 /** @var bool */
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
55 /** @var string */
56 protected $mServer;
57 /** @var string */
58 protected $mUser;
59 /** @var string */
60 protected $mPassword;
61 /** @var string */
62 protected $mDBname;
63 /** @var bool */
64 protected $cliMode;
65
66 /** @var BagOStuff APC cache */
67 protected $srvCache;
68 /** @var LoggerInterface */
69 protected $connLogger;
70 /** @var LoggerInterface */
71 protected $queryLogger;
72 /** @var callback Error logging callback */
73 protected $errorLogger;
74
75 /** @var resource Database connection */
76 protected $mConn = null;
77 /** @var bool */
78 protected $mOpened = false;
79
80 /** @var array[] List of (callable, method name) */
81 protected $mTrxIdleCallbacks = [];
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxPreCommitCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxEndCallbacks = [];
86 /** @var array[] Map of (name => (callable, method name)) */
87 protected $mTrxRecurringCallbacks = [];
88 /** @var bool Whether to suppress triggering of transaction end callbacks */
89 protected $mTrxEndCallbacksSuppressed = false;
90
91 /** @var string */
92 protected $mTablePrefix;
93 /** @var string */
94 protected $mSchema;
95 /** @var integer */
96 protected $mFlags;
97 /** @var bool */
98 protected $mForeign;
99 /** @var array */
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
105 /** @var array */
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
111 /** @var string */
112 protected $delimiter = ';';
113
114 /**
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
117 *
118 * @var int
119 */
120 protected $mTrxLevel = 0;
121 /**
122 * Either a short hexidecimal string if a transaction is active or ""
123 *
124 * @var string
125 * @see DatabaseBase::mTrxLevel
126 */
127 protected $mTrxShortId = '';
128 /**
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
132 *
133 * @var float|null
134 * @see DatabaseBase::mTrxLevel
135 */
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
139 /**
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
142 *
143 * @var string
144 * @see DatabaseBase::mTrxLevel
145 */
146 private $mTrxFname = null;
147 /**
148 * Record if possible write queries were done in the last transaction started
149 *
150 * @var bool
151 * @see DatabaseBase::mTrxLevel
152 */
153 private $mTrxDoneWrites = false;
154 /**
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
156 *
157 * @var bool
158 * @see DatabaseBase::mTrxLevel
159 */
160 private $mTrxAutomatic = false;
161 /**
162 * Array of levels of atomicity within transactions
163 *
164 * @var array
165 */
166 private $mTrxAtomicLevels = [];
167 /**
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
169 *
170 * @var bool
171 */
172 private $mTrxAutomaticAtomic = false;
173 /**
174 * Track the write query callers of the current transaction
175 *
176 * @var string[]
177 */
178 private $mTrxWriteCallers = [];
179 /**
180 * @var float Seconds spent in write queries for the current transaction
181 */
182 private $mTrxWriteDuration = 0.0;
183 /**
184 * @var integer Number of write queries for the current transaction
185 */
186 private $mTrxWriteQueryCount = 0;
187 /**
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
189 */
190 private $mTrxWriteAdjDuration = 0.0;
191 /**
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
193 */
194 private $mTrxWriteAdjQueryCount = 0;
195 /**
196 * @var float RTT time estimate
197 */
198 private $mRTTEstimate = 0.0;
199
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
202
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
205
206 /**
207 * @since 1.21
208 * @var resource File handle for upgrade
209 */
210 protected $fileHandle = null;
211
212 /**
213 * @since 1.22
214 * @var string[] Process cache of VIEWs names in the database
215 */
216 protected $allViews = null;
217
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
220
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
223
224 /** @var Profiler */
225 protected $profiler;
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
228
229 /**
230 * Constructor.
231 *
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
235 *
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
238 *
239 * @param array $params Parameters passed from DatabaseBase::factory()
240 */
241 function __construct( array $params ) {
242 global $wgDBprefix, $wgDBmwschema;
243
244 $this->srvCache = ObjectCache::getLocalServerInstance( 'hash' );
245
246 $server = $params['host'];
247 $user = $params['user'];
248 $password = $params['password'];
249 $dbName = $params['dbname'];
250 $flags = $params['flags'];
251 $tablePrefix = $params['tablePrefix'];
252 $schema = $params['schema'];
253 $foreign = $params['foreign'];
254
255 $this->cliMode = isset( $params['cliMode'] )
256 ? $params['cliMode']
257 : ( PHP_SAPI === 'cli' );
258
259 $this->mFlags = $flags;
260 if ( $this->mFlags & DBO_DEFAULT ) {
261 if ( $this->cliMode ) {
262 $this->mFlags &= ~DBO_TRX;
263 } else {
264 $this->mFlags |= DBO_TRX;
265 }
266 }
267
268 $this->mSessionVars = $params['variables'];
269
270 /** Get the default table prefix*/
271 if ( $tablePrefix === 'get from global' ) {
272 $this->mTablePrefix = $wgDBprefix;
273 } else {
274 $this->mTablePrefix = $tablePrefix;
275 }
276
277 /** Get the database schema*/
278 if ( $schema === 'get from global' ) {
279 $this->mSchema = $wgDBmwschema;
280 } else {
281 $this->mSchema = $schema;
282 }
283
284 $this->mForeign = $foreign;
285
286 $this->profiler = isset( $params['profiler'] )
287 ? $params['profiler']
288 : Profiler::instance(); // @TODO: remove global state
289 $this->trxProfiler = isset( $params['trxProfiler'] )
290 ? $params['trxProfiler']
291 : new TransactionProfiler();
292 $this->connLogger = isset( $params['connLogger'] )
293 ? $params['connLogger']
294 : new \Psr\Log\NullLogger();
295 $this->queryLogger = isset( $params['queryLogger'] )
296 ? $params['queryLogger']
297 : new \Psr\Log\NullLogger();
298
299 if ( $user ) {
300 $this->open( $server, $user, $password, $dbName );
301 }
302 }
303
304 /**
305 * Given a DB type, construct the name of the appropriate child class of
306 * IDatabase. This is designed to replace all of the manual stuff like:
307 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
308 * as well as validate against the canonical list of DB types we have
309 *
310 * This factory function is mostly useful for when you need to connect to a
311 * database other than the MediaWiki default (such as for external auth,
312 * an extension, et cetera). Do not use this to connect to the MediaWiki
313 * database. Example uses in core:
314 * @see LoadBalancer::reallyOpenConnection()
315 * @see ForeignDBRepo::getMasterDB()
316 * @see WebInstallerDBConnect::execute()
317 *
318 * @since 1.18
319 *
320 * @param string $dbType A possible DB type
321 * @param array $p An array of options to pass to the constructor.
322 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
323 * @return IDatabase|null If the database driver or extension cannot be found
324 * @throws InvalidArgumentException If the database driver or extension cannot be found
325 */
326 final public static function factory( $dbType, $p = [] ) {
327 global $wgCommandLineMode;
328
329 $canonicalDBTypes = [
330 'mysql' => [ 'mysqli', 'mysql' ],
331 'postgres' => [],
332 'sqlite' => [],
333 'oracle' => [],
334 'mssql' => [],
335 ];
336
337 $driver = false;
338 $dbType = strtolower( $dbType );
339 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
340 $possibleDrivers = $canonicalDBTypes[$dbType];
341 if ( !empty( $p['driver'] ) ) {
342 if ( in_array( $p['driver'], $possibleDrivers ) ) {
343 $driver = $p['driver'];
344 } else {
345 throw new InvalidArgumentException( __METHOD__ .
346 " type '$dbType' does not support driver '{$p['driver']}'" );
347 }
348 } else {
349 foreach ( $possibleDrivers as $posDriver ) {
350 if ( extension_loaded( $posDriver ) ) {
351 $driver = $posDriver;
352 break;
353 }
354 }
355 }
356 } else {
357 $driver = $dbType;
358 }
359 if ( $driver === false ) {
360 throw new InvalidArgumentException( __METHOD__ .
361 " no viable database extension found for type '$dbType'" );
362 }
363
364 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
365 // and everything else doesn't use a schema (e.g. null)
366 // Although postgres and oracle support schemas, we don't use them (yet)
367 // to maintain backwards compatibility
368 $defaultSchemas = [
369 'mssql' => 'get from global',
370 ];
371
372 $class = 'Database' . ucfirst( $driver );
373 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
374 // Resolve some defaults for b/c
375 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
376 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
377 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
378 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
379 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
380 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
381 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
382 if ( !isset( $p['schema'] ) ) {
383 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
384 }
385 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
386 $p['cliMode'] = $wgCommandLineMode;
387
388 $conn = new $class( $p );
389 if ( isset( $p['connLogger'] ) ) {
390 $conn->connLogger = $p['connLogger'];
391 }
392 if ( isset( $p['queryLogger'] ) ) {
393 $conn->queryLogger = $p['queryLogger'];
394 }
395 if ( isset( $p['errorLogger'] ) ) {
396 $conn->errorLogger = $p['errorLogger'];
397 } else {
398 $conn->errorLogger = [ MWExceptionHandler::class, 'logException' ];
399 }
400 } else {
401 $conn = null;
402 }
403
404 return $conn;
405 }
406
407 public function setLogger( LoggerInterface $logger ) {
408 $this->queryLogger = $logger;
409 }
410
411 public function getServerInfo() {
412 return $this->getServerVersion();
413 }
414
415 /**
416 * @return string Command delimiter used by this database engine
417 */
418 public function getDelimiter() {
419 return $this->delimiter;
420 }
421
422 /**
423 * Boolean, controls output of large amounts of debug information.
424 * @param bool|null $debug
425 * - true to enable debugging
426 * - false to disable debugging
427 * - omitted or null to do nothing
428 *
429 * @return bool|null Previous value of the flag
430 */
431 public function debug( $debug = null ) {
432 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
433 }
434
435 public function bufferResults( $buffer = null ) {
436 if ( is_null( $buffer ) ) {
437 return !(bool)( $this->mFlags & DBO_NOBUFFER );
438 } else {
439 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
440 }
441 }
442
443 /**
444 * Turns on (false) or off (true) the automatic generation and sending
445 * of a "we're sorry, but there has been a database error" page on
446 * database errors. Default is on (false). When turned off, the
447 * code should use lastErrno() and lastError() to handle the
448 * situation as appropriate.
449 *
450 * Do not use this function outside of the Database classes.
451 *
452 * @param null|bool $ignoreErrors
453 * @return bool The previous value of the flag.
454 */
455 protected function ignoreErrors( $ignoreErrors = null ) {
456 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
457 }
458
459 public function trxLevel() {
460 return $this->mTrxLevel;
461 }
462
463 public function trxTimestamp() {
464 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
465 }
466
467 public function tablePrefix( $prefix = null ) {
468 return wfSetVar( $this->mTablePrefix, $prefix );
469 }
470
471 public function dbSchema( $schema = null ) {
472 return wfSetVar( $this->mSchema, $schema );
473 }
474
475 /**
476 * Set the filehandle to copy write statements to.
477 *
478 * @param resource $fh File handle
479 */
480 public function setFileHandle( $fh ) {
481 $this->fileHandle = $fh;
482 }
483
484 public function getLBInfo( $name = null ) {
485 if ( is_null( $name ) ) {
486 return $this->mLBInfo;
487 } else {
488 if ( array_key_exists( $name, $this->mLBInfo ) ) {
489 return $this->mLBInfo[$name];
490 } else {
491 return null;
492 }
493 }
494 }
495
496 public function setLBInfo( $name, $value = null ) {
497 if ( is_null( $value ) ) {
498 $this->mLBInfo = $name;
499 } else {
500 $this->mLBInfo[$name] = $value;
501 }
502 }
503
504 public function setLazyMasterHandle( IDatabase $conn ) {
505 $this->lazyMasterHandle = $conn;
506 }
507
508 /**
509 * @return IDatabase|null
510 * @see setLazyMasterHandle()
511 * @since 1.27
512 */
513 public function getLazyMasterHandle() {
514 return $this->lazyMasterHandle;
515 }
516
517 /**
518 * @param TransactionProfiler $profiler
519 * @since 1.27
520 */
521 public function setTransactionProfiler( TransactionProfiler $profiler ) {
522 $this->trxProfiler = $profiler;
523 }
524
525 /**
526 * Returns true if this database supports (and uses) cascading deletes
527 *
528 * @return bool
529 */
530 public function cascadingDeletes() {
531 return false;
532 }
533
534 /**
535 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
536 *
537 * @return bool
538 */
539 public function cleanupTriggers() {
540 return false;
541 }
542
543 /**
544 * Returns true if this database is strict about what can be put into an IP field.
545 * Specifically, it uses a NULL value instead of an empty string.
546 *
547 * @return bool
548 */
549 public function strictIPs() {
550 return false;
551 }
552
553 /**
554 * Returns true if this database uses timestamps rather than integers
555 *
556 * @return bool
557 */
558 public function realTimestamps() {
559 return false;
560 }
561
562 public function implicitGroupby() {
563 return true;
564 }
565
566 public function implicitOrderby() {
567 return true;
568 }
569
570 /**
571 * Returns true if this database can do a native search on IP columns
572 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
573 *
574 * @return bool
575 */
576 public function searchableIPs() {
577 return false;
578 }
579
580 /**
581 * Returns true if this database can use functional indexes
582 *
583 * @return bool
584 */
585 public function functionalIndexes() {
586 return false;
587 }
588
589 public function lastQuery() {
590 return $this->mLastQuery;
591 }
592
593 public function doneWrites() {
594 return (bool)$this->mDoneWrites;
595 }
596
597 public function lastDoneWrites() {
598 return $this->mDoneWrites ?: false;
599 }
600
601 public function writesPending() {
602 return $this->mTrxLevel && $this->mTrxDoneWrites;
603 }
604
605 public function writesOrCallbacksPending() {
606 return $this->mTrxLevel && (
607 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
608 );
609 }
610
611 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
612 if ( !$this->mTrxLevel ) {
613 return false;
614 } elseif ( !$this->mTrxDoneWrites ) {
615 return 0.0;
616 }
617
618 switch ( $type ) {
619 case self::ESTIMATE_DB_APPLY:
620 $this->ping( $rtt );
621 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
622 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
623 // For omitted queries, make them count as something at least
624 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
625 $applyTime += self::TINY_WRITE_SEC * $omitted;
626
627 return $applyTime;
628 default: // everything
629 return $this->mTrxWriteDuration;
630 }
631 }
632
633 public function pendingWriteCallers() {
634 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
635 }
636
637 public function isOpen() {
638 return $this->mOpened;
639 }
640
641 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
642 if ( $remember === self::REMEMBER_PRIOR ) {
643 array_push( $this->priorFlags, $this->mFlags );
644 }
645 $this->mFlags |= $flag;
646 }
647
648 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
649 if ( $remember === self::REMEMBER_PRIOR ) {
650 array_push( $this->priorFlags, $this->mFlags );
651 }
652 $this->mFlags &= ~$flag;
653 }
654
655 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
656 if ( !$this->priorFlags ) {
657 return;
658 }
659
660 if ( $state === self::RESTORE_INITIAL ) {
661 $this->mFlags = reset( $this->priorFlags );
662 $this->priorFlags = [];
663 } else {
664 $this->mFlags = array_pop( $this->priorFlags );
665 }
666 }
667
668 public function getFlag( $flag ) {
669 return !!( $this->mFlags & $flag );
670 }
671
672 public function getProperty( $name ) {
673 return $this->$name;
674 }
675
676 public function getWikiID() {
677 if ( $this->mTablePrefix ) {
678 return "{$this->mDBname}-{$this->mTablePrefix}";
679 } else {
680 return $this->mDBname;
681 }
682 }
683
684 /**
685 * Get information about an index into an object
686 * @param string $table Table name
687 * @param string $index Index name
688 * @param string $fname Calling function name
689 * @return mixed Database-specific index description class or false if the index does not exist
690 */
691 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
692
693 /**
694 * Wrapper for addslashes()
695 *
696 * @param string $s String to be slashed.
697 * @return string Slashed string.
698 */
699 abstract function strencode( $s );
700
701 /**
702 * Called by serialize. Throw an exception when DB connection is serialized.
703 * This causes problems on some database engines because the connection is
704 * not restored on unserialize.
705 */
706 public function __sleep() {
707 throw new RuntimeException( 'Database serialization may cause problems, since ' .
708 'the connection is not restored on wakeup.' );
709 }
710
711 protected function installErrorHandler() {
712 $this->mPHPError = false;
713 $this->htmlErrors = ini_set( 'html_errors', '0' );
714 set_error_handler( [ $this, 'connectionerrorLogger' ] );
715 }
716
717 /**
718 * @return bool|string
719 */
720 protected function restoreErrorHandler() {
721 restore_error_handler();
722 if ( $this->htmlErrors !== false ) {
723 ini_set( 'html_errors', $this->htmlErrors );
724 }
725 if ( $this->mPHPError ) {
726 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
727 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
728
729 return $error;
730 } else {
731 return false;
732 }
733 }
734
735 /**
736 * @param int $errno
737 * @param string $errstr
738 */
739 public function connectionerrorLogger( $errno, $errstr ) {
740 $this->mPHPError = $errstr;
741 }
742
743 /**
744 * Create a log context to pass to PSR logging functions.
745 *
746 * @param array $extras Additional data to add to context
747 * @return array
748 */
749 protected function getLogContext( array $extras = [] ) {
750 return array_merge(
751 [
752 'db_server' => $this->mServer,
753 'db_name' => $this->mDBname,
754 'db_user' => $this->mUser,
755 ],
756 $extras
757 );
758 }
759
760 public function close() {
761 if ( $this->mConn ) {
762 if ( $this->trxLevel() ) {
763 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
764 }
765
766 $closed = $this->closeConnection();
767 $this->mConn = false;
768 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
769 throw new RuntimeException( "Transaction callbacks still pending." );
770 } else {
771 $closed = true;
772 }
773 $this->mOpened = false;
774
775 return $closed;
776 }
777
778 /**
779 * Make sure isOpen() returns true as a sanity check
780 *
781 * @throws DBUnexpectedError
782 */
783 protected function assertOpen() {
784 if ( !$this->isOpen() ) {
785 throw new DBUnexpectedError( $this, "DB connection was already closed." );
786 }
787 }
788
789 /**
790 * Closes underlying database connection
791 * @since 1.20
792 * @return bool Whether connection was closed successfully
793 */
794 abstract protected function closeConnection();
795
796 function reportConnectionError( $error = 'Unknown error' ) {
797 $myError = $this->lastError();
798 if ( $myError ) {
799 $error = $myError;
800 }
801
802 # New method
803 throw new DBConnectionError( $this, $error );
804 }
805
806 /**
807 * The DBMS-dependent part of query()
808 *
809 * @param string $sql SQL query.
810 * @return ResultWrapper|bool Result object to feed to fetchObject,
811 * fetchRow, ...; or false on failure
812 */
813 abstract protected function doQuery( $sql );
814
815 /**
816 * Determine whether a query writes to the DB.
817 * Should return true if unsure.
818 *
819 * @param string $sql
820 * @return bool
821 */
822 protected function isWriteQuery( $sql ) {
823 return !preg_match(
824 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
825 }
826
827 /**
828 * @param $sql
829 * @return string|null
830 */
831 protected function getQueryVerb( $sql ) {
832 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
833 }
834
835 /**
836 * Determine whether a SQL statement is sensitive to isolation level.
837 * A SQL statement is considered transactable if its result could vary
838 * depending on the transaction isolation level. Operational commands
839 * such as 'SET' and 'SHOW' are not considered to be transactable.
840 *
841 * @param string $sql
842 * @return bool
843 */
844 protected function isTransactableQuery( $sql ) {
845 $verb = $this->getQueryVerb( $sql );
846 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
847 }
848
849 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
850 global $wgUser;
851
852 $priorWritesPending = $this->writesOrCallbacksPending();
853 $this->mLastQuery = $sql;
854
855 $isWrite = $this->isWriteQuery( $sql );
856 if ( $isWrite ) {
857 $reason = $this->getReadOnlyReason();
858 if ( $reason !== false ) {
859 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
860 }
861 # Set a flag indicating that writes have been done
862 $this->mDoneWrites = microtime( true );
863 }
864
865 # Add a comment for easy SHOW PROCESSLIST interpretation
866 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
867 $userName = $wgUser->getName();
868 if ( mb_strlen( $userName ) > 15 ) {
869 $userName = mb_substr( $userName, 0, 15 ) . '...';
870 }
871 $userName = str_replace( '/', '', $userName );
872 } else {
873 $userName = '';
874 }
875
876 // Add trace comment to the begin of the sql string, right after the operator.
877 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
878 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
879
880 # Start implicit transactions that wrap the request if DBO_TRX is enabled
881 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX )
882 && $this->isTransactableQuery( $sql )
883 ) {
884 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
885 $this->mTrxAutomatic = true;
886 }
887
888 # Keep track of whether the transaction has write queries pending
889 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
890 $this->mTrxDoneWrites = true;
891 $this->trxProfiler->transactionWritingIn(
892 $this->mServer, $this->mDBname, $this->mTrxShortId );
893 }
894
895 if ( $this->debug() ) {
896 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
897 }
898
899 # Avoid fatals if close() was called
900 $this->assertOpen();
901
902 # Send the query to the server
903 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
904
905 # Try reconnecting if the connection was lost
906 if ( false === $ret && $this->wasErrorReissuable() ) {
907 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
908 # Stash the last error values before anything might clear them
909 $lastError = $this->lastError();
910 $lastErrno = $this->lastErrno();
911 # Update state tracking to reflect transaction loss due to disconnection
912 $this->handleTransactionLoss();
913 if ( $this->reconnect() ) {
914 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
915 $this->connLogger->warning( $msg );
916 $this->queryLogger->warning(
917 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
918
919 if ( !$recoverable ) {
920 # Callers may catch the exception and continue to use the DB
921 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
922 } else {
923 # Should be safe to silently retry the query
924 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
925 }
926 } else {
927 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
928 $this->connLogger->error( $msg );
929 }
930 }
931
932 if ( false === $ret ) {
933 # Deadlocks cause the entire transaction to abort, not just the statement.
934 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
935 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
936 if ( $this->wasDeadlock() ) {
937 if ( $this->explicitTrxActive() || $priorWritesPending ) {
938 $tempIgnore = false; // not recoverable
939 }
940 # Update state tracking to reflect transaction loss
941 $this->handleTransactionLoss();
942 }
943
944 $this->reportQueryError(
945 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
946 }
947
948 $res = $this->resultObject( $ret );
949
950 return $res;
951 }
952
953 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
954 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
955 # generalizeSQL() will probably cut down the query to reasonable
956 # logging size most of the time. The substr is really just a sanity check.
957 if ( $isMaster ) {
958 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
959 } else {
960 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
961 }
962
963 # Include query transaction state
964 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
965
966 $startTime = microtime( true );
967 $this->profiler->profileIn( $queryProf );
968 $ret = $this->doQuery( $commentedSql );
969 $this->profiler->profileOut( $queryProf );
970 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
971
972 unset( $queryProfSection ); // profile out (if set)
973
974 if ( $ret !== false ) {
975 $this->lastPing = $startTime;
976 if ( $isWrite && $this->mTrxLevel ) {
977 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
978 $this->mTrxWriteCallers[] = $fname;
979 }
980 }
981
982 if ( $sql === self::PING_QUERY ) {
983 $this->mRTTEstimate = $queryRuntime;
984 }
985
986 $this->trxProfiler->recordQueryCompletion(
987 $queryProf, $startTime, $isWrite, $this->affectedRows()
988 );
989 MWDebug::query( $sql, $fname, $isMaster, $queryRuntime );
990
991 return $ret;
992 }
993
994 /**
995 * Update the estimated run-time of a query, not counting large row lock times
996 *
997 * LoadBalancer can be set to rollback transactions that will create huge replication
998 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
999 * queries, like inserting a row can take a long time due to row locking. This method
1000 * uses some simple heuristics to discount those cases.
1001 *
1002 * @param string $sql A SQL write query
1003 * @param float $runtime Total runtime, including RTT
1004 */
1005 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1006 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1007 $indicativeOfReplicaRuntime = true;
1008 if ( $runtime > self::SLOW_WRITE_SEC ) {
1009 $verb = $this->getQueryVerb( $sql );
1010 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1011 if ( $verb === 'INSERT' ) {
1012 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1013 } elseif ( $verb === 'REPLACE' ) {
1014 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1015 }
1016 }
1017
1018 $this->mTrxWriteDuration += $runtime;
1019 $this->mTrxWriteQueryCount += 1;
1020 if ( $indicativeOfReplicaRuntime ) {
1021 $this->mTrxWriteAdjDuration += $runtime;
1022 $this->mTrxWriteAdjQueryCount += 1;
1023 }
1024 }
1025
1026 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1027 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1028 # Dropped connections also mean that named locks are automatically released.
1029 # Only allow error suppression in autocommit mode or when the lost transaction
1030 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1031 if ( $this->mNamedLocksHeld ) {
1032 return false; // possible critical section violation
1033 } elseif ( $sql === 'COMMIT' ) {
1034 return !$priorWritesPending; // nothing written anyway? (T127428)
1035 } elseif ( $sql === 'ROLLBACK' ) {
1036 return true; // transaction lost...which is also what was requested :)
1037 } elseif ( $this->explicitTrxActive() ) {
1038 return false; // don't drop atomocity
1039 } elseif ( $priorWritesPending ) {
1040 return false; // prior writes lost from implicit transaction
1041 }
1042
1043 return true;
1044 }
1045
1046 private function handleTransactionLoss() {
1047 $this->mTrxLevel = 0;
1048 $this->mTrxIdleCallbacks = []; // bug 65263
1049 $this->mTrxPreCommitCallbacks = []; // bug 65263
1050 try {
1051 // Handle callbacks in mTrxEndCallbacks
1052 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1053 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1054 return null;
1055 } catch ( Exception $e ) {
1056 // Already logged; move on...
1057 return $e;
1058 }
1059 }
1060
1061 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1062 if ( $this->ignoreErrors() || $tempIgnore ) {
1063 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1064 } else {
1065 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1066 $this->queryLogger->error(
1067 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1068 $this->getLogContext( [
1069 'method' => __METHOD__,
1070 'errno' => $errno,
1071 'error' => $error,
1072 'sql1line' => $sql1line,
1073 'fname' => $fname,
1074 ] )
1075 );
1076 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1077 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1078 }
1079 }
1080
1081 /**
1082 * Intended to be compatible with the PEAR::DB wrapper functions.
1083 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1084 *
1085 * ? = scalar value, quoted as necessary
1086 * ! = raw SQL bit (a function for instance)
1087 * & = filename; reads the file and inserts as a blob
1088 * (we don't use this though...)
1089 *
1090 * @param string $sql
1091 * @param string $func
1092 *
1093 * @return array
1094 */
1095 protected function prepare( $sql, $func = __METHOD__ ) {
1096 /* MySQL doesn't support prepared statements (yet), so just
1097 * pack up the query for reference. We'll manually replace
1098 * the bits later.
1099 */
1100 return [ 'query' => $sql, 'func' => $func ];
1101 }
1102
1103 /**
1104 * Free a prepared query, generated by prepare().
1105 * @param string $prepared
1106 */
1107 protected function freePrepared( $prepared ) {
1108 /* No-op by default */
1109 }
1110
1111 /**
1112 * Execute a prepared query with the various arguments
1113 * @param string $prepared The prepared sql
1114 * @param mixed $args Either an array here, or put scalars as varargs
1115 *
1116 * @return ResultWrapper
1117 */
1118 public function execute( $prepared, $args = null ) {
1119 if ( !is_array( $args ) ) {
1120 # Pull the var args
1121 $args = func_get_args();
1122 array_shift( $args );
1123 }
1124
1125 $sql = $this->fillPrepared( $prepared['query'], $args );
1126
1127 return $this->query( $sql, $prepared['func'] );
1128 }
1129
1130 /**
1131 * For faking prepared SQL statements on DBs that don't support it directly.
1132 *
1133 * @param string $preparedQuery A 'preparable' SQL statement
1134 * @param array $args Array of Arguments to fill it with
1135 * @return string Executable SQL
1136 */
1137 public function fillPrepared( $preparedQuery, $args ) {
1138 reset( $args );
1139 $this->preparedArgs =& $args;
1140
1141 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1142 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1143 }
1144
1145 /**
1146 * preg_callback func for fillPrepared()
1147 * The arguments should be in $this->preparedArgs and must not be touched
1148 * while we're doing this.
1149 *
1150 * @param array $matches
1151 * @throws DBUnexpectedError
1152 * @return string
1153 */
1154 protected function fillPreparedArg( $matches ) {
1155 switch ( $matches[1] ) {
1156 case '\\?':
1157 return '?';
1158 case '\\!':
1159 return '!';
1160 case '\\&':
1161 return '&';
1162 }
1163
1164 list( /* $n */, $arg ) = each( $this->preparedArgs );
1165
1166 switch ( $matches[1] ) {
1167 case '?':
1168 return $this->addQuotes( $arg );
1169 case '!':
1170 return $arg;
1171 case '&':
1172 # return $this->addQuotes( file_get_contents( $arg ) );
1173 throw new DBUnexpectedError(
1174 $this,
1175 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1176 );
1177 default:
1178 throw new DBUnexpectedError(
1179 $this,
1180 'Received invalid match. This should never happen!'
1181 );
1182 }
1183 }
1184
1185 public function freeResult( $res ) {
1186 }
1187
1188 public function selectField(
1189 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1190 ) {
1191 if ( $var === '*' ) { // sanity
1192 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1193 }
1194
1195 if ( !is_array( $options ) ) {
1196 $options = [ $options ];
1197 }
1198
1199 $options['LIMIT'] = 1;
1200
1201 $res = $this->select( $table, $var, $cond, $fname, $options );
1202 if ( $res === false || !$this->numRows( $res ) ) {
1203 return false;
1204 }
1205
1206 $row = $this->fetchRow( $res );
1207
1208 if ( $row !== false ) {
1209 return reset( $row );
1210 } else {
1211 return false;
1212 }
1213 }
1214
1215 public function selectFieldValues(
1216 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1217 ) {
1218 if ( $var === '*' ) { // sanity
1219 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1220 } elseif ( !is_string( $var ) ) { // sanity
1221 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1222 }
1223
1224 if ( !is_array( $options ) ) {
1225 $options = [ $options ];
1226 }
1227
1228 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1229 if ( $res === false ) {
1230 return false;
1231 }
1232
1233 $values = [];
1234 foreach ( $res as $row ) {
1235 $values[] = $row->$var;
1236 }
1237
1238 return $values;
1239 }
1240
1241 /**
1242 * Returns an optional USE INDEX clause to go after the table, and a
1243 * string to go at the end of the query.
1244 *
1245 * @param array $options Associative array of options to be turned into
1246 * an SQL query, valid keys are listed in the function.
1247 * @return array
1248 * @see DatabaseBase::select()
1249 */
1250 public function makeSelectOptions( $options ) {
1251 $preLimitTail = $postLimitTail = '';
1252 $startOpts = '';
1253
1254 $noKeyOptions = [];
1255
1256 foreach ( $options as $key => $option ) {
1257 if ( is_numeric( $key ) ) {
1258 $noKeyOptions[$option] = true;
1259 }
1260 }
1261
1262 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1263
1264 $preLimitTail .= $this->makeOrderBy( $options );
1265
1266 // if (isset($options['LIMIT'])) {
1267 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1268 // isset($options['OFFSET']) ? $options['OFFSET']
1269 // : false);
1270 // }
1271
1272 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1273 $postLimitTail .= ' FOR UPDATE';
1274 }
1275
1276 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1277 $postLimitTail .= ' LOCK IN SHARE MODE';
1278 }
1279
1280 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1281 $startOpts .= 'DISTINCT';
1282 }
1283
1284 # Various MySQL extensions
1285 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1286 $startOpts .= ' /*! STRAIGHT_JOIN */';
1287 }
1288
1289 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1290 $startOpts .= ' HIGH_PRIORITY';
1291 }
1292
1293 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1294 $startOpts .= ' SQL_BIG_RESULT';
1295 }
1296
1297 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1298 $startOpts .= ' SQL_BUFFER_RESULT';
1299 }
1300
1301 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1302 $startOpts .= ' SQL_SMALL_RESULT';
1303 }
1304
1305 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1306 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1307 }
1308
1309 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1310 $startOpts .= ' SQL_CACHE';
1311 }
1312
1313 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1314 $startOpts .= ' SQL_NO_CACHE';
1315 }
1316
1317 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1318 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1319 } else {
1320 $useIndex = '';
1321 }
1322 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1323 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1324 } else {
1325 $ignoreIndex = '';
1326 }
1327
1328 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1329 }
1330
1331 /**
1332 * Returns an optional GROUP BY with an optional HAVING
1333 *
1334 * @param array $options Associative array of options
1335 * @return string
1336 * @see DatabaseBase::select()
1337 * @since 1.21
1338 */
1339 public function makeGroupByWithHaving( $options ) {
1340 $sql = '';
1341 if ( isset( $options['GROUP BY'] ) ) {
1342 $gb = is_array( $options['GROUP BY'] )
1343 ? implode( ',', $options['GROUP BY'] )
1344 : $options['GROUP BY'];
1345 $sql .= ' GROUP BY ' . $gb;
1346 }
1347 if ( isset( $options['HAVING'] ) ) {
1348 $having = is_array( $options['HAVING'] )
1349 ? $this->makeList( $options['HAVING'], LIST_AND )
1350 : $options['HAVING'];
1351 $sql .= ' HAVING ' . $having;
1352 }
1353
1354 return $sql;
1355 }
1356
1357 /**
1358 * Returns an optional ORDER BY
1359 *
1360 * @param array $options Associative array of options
1361 * @return string
1362 * @see DatabaseBase::select()
1363 * @since 1.21
1364 */
1365 public function makeOrderBy( $options ) {
1366 if ( isset( $options['ORDER BY'] ) ) {
1367 $ob = is_array( $options['ORDER BY'] )
1368 ? implode( ',', $options['ORDER BY'] )
1369 : $options['ORDER BY'];
1370
1371 return ' ORDER BY ' . $ob;
1372 }
1373
1374 return '';
1375 }
1376
1377 // See IDatabase::select for the docs for this function
1378 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1379 $options = [], $join_conds = [] ) {
1380 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1381
1382 return $this->query( $sql, $fname );
1383 }
1384
1385 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1386 $options = [], $join_conds = []
1387 ) {
1388 if ( is_array( $vars ) ) {
1389 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1390 }
1391
1392 $options = (array)$options;
1393 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1394 ? $options['USE INDEX']
1395 : [];
1396 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1397 ? $options['IGNORE INDEX']
1398 : [];
1399
1400 if ( is_array( $table ) ) {
1401 $from = ' FROM ' .
1402 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1403 } elseif ( $table != '' ) {
1404 if ( $table[0] == ' ' ) {
1405 $from = ' FROM ' . $table;
1406 } else {
1407 $from = ' FROM ' .
1408 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1409 }
1410 } else {
1411 $from = '';
1412 }
1413
1414 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1415 $this->makeSelectOptions( $options );
1416
1417 if ( !empty( $conds ) ) {
1418 if ( is_array( $conds ) ) {
1419 $conds = $this->makeList( $conds, LIST_AND );
1420 }
1421 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1422 } else {
1423 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1424 }
1425
1426 if ( isset( $options['LIMIT'] ) ) {
1427 $sql = $this->limitResult( $sql, $options['LIMIT'],
1428 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1429 }
1430 $sql = "$sql $postLimitTail";
1431
1432 if ( isset( $options['EXPLAIN'] ) ) {
1433 $sql = 'EXPLAIN ' . $sql;
1434 }
1435
1436 return $sql;
1437 }
1438
1439 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1440 $options = [], $join_conds = []
1441 ) {
1442 $options = (array)$options;
1443 $options['LIMIT'] = 1;
1444 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1445
1446 if ( $res === false ) {
1447 return false;
1448 }
1449
1450 if ( !$this->numRows( $res ) ) {
1451 return false;
1452 }
1453
1454 $obj = $this->fetchObject( $res );
1455
1456 return $obj;
1457 }
1458
1459 public function estimateRowCount(
1460 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1461 ) {
1462 $rows = 0;
1463 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1464
1465 if ( $res ) {
1466 $row = $this->fetchRow( $res );
1467 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1468 }
1469
1470 return $rows;
1471 }
1472
1473 public function selectRowCount(
1474 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1475 ) {
1476 $rows = 0;
1477 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1478 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1479
1480 if ( $res ) {
1481 $row = $this->fetchRow( $res );
1482 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1483 }
1484
1485 return $rows;
1486 }
1487
1488 /**
1489 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1490 * It's only slightly flawed. Don't use for anything important.
1491 *
1492 * @param string $sql A SQL Query
1493 *
1494 * @return string
1495 */
1496 protected static function generalizeSQL( $sql ) {
1497 # This does the same as the regexp below would do, but in such a way
1498 # as to avoid crashing php on some large strings.
1499 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1500
1501 $sql = str_replace( "\\\\", '', $sql );
1502 $sql = str_replace( "\\'", '', $sql );
1503 $sql = str_replace( "\\\"", '', $sql );
1504 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1505 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1506
1507 # All newlines, tabs, etc replaced by single space
1508 $sql = preg_replace( '/\s+/', ' ', $sql );
1509
1510 # All numbers => N,
1511 # except the ones surrounded by characters, e.g. l10n
1512 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1513 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1514
1515 return $sql;
1516 }
1517
1518 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1519 $info = $this->fieldInfo( $table, $field );
1520
1521 return (bool)$info;
1522 }
1523
1524 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1525 if ( !$this->tableExists( $table ) ) {
1526 return null;
1527 }
1528
1529 $info = $this->indexInfo( $table, $index, $fname );
1530 if ( is_null( $info ) ) {
1531 return null;
1532 } else {
1533 return $info !== false;
1534 }
1535 }
1536
1537 public function tableExists( $table, $fname = __METHOD__ ) {
1538 $table = $this->tableName( $table );
1539 $old = $this->ignoreErrors( true );
1540 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1541 $this->ignoreErrors( $old );
1542
1543 return (bool)$res;
1544 }
1545
1546 public function indexUnique( $table, $index ) {
1547 $indexInfo = $this->indexInfo( $table, $index );
1548
1549 if ( !$indexInfo ) {
1550 return null;
1551 }
1552
1553 return !$indexInfo[0]->Non_unique;
1554 }
1555
1556 /**
1557 * Helper for DatabaseBase::insert().
1558 *
1559 * @param array $options
1560 * @return string
1561 */
1562 protected function makeInsertOptions( $options ) {
1563 return implode( ' ', $options );
1564 }
1565
1566 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1567 # No rows to insert, easy just return now
1568 if ( !count( $a ) ) {
1569 return true;
1570 }
1571
1572 $table = $this->tableName( $table );
1573
1574 if ( !is_array( $options ) ) {
1575 $options = [ $options ];
1576 }
1577
1578 $fh = null;
1579 if ( isset( $options['fileHandle'] ) ) {
1580 $fh = $options['fileHandle'];
1581 }
1582 $options = $this->makeInsertOptions( $options );
1583
1584 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1585 $multi = true;
1586 $keys = array_keys( $a[0] );
1587 } else {
1588 $multi = false;
1589 $keys = array_keys( $a );
1590 }
1591
1592 $sql = 'INSERT ' . $options .
1593 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1594
1595 if ( $multi ) {
1596 $first = true;
1597 foreach ( $a as $row ) {
1598 if ( $first ) {
1599 $first = false;
1600 } else {
1601 $sql .= ',';
1602 }
1603 $sql .= '(' . $this->makeList( $row ) . ')';
1604 }
1605 } else {
1606 $sql .= '(' . $this->makeList( $a ) . ')';
1607 }
1608
1609 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1610 return false;
1611 } elseif ( $fh !== null ) {
1612 return true;
1613 }
1614
1615 return (bool)$this->query( $sql, $fname );
1616 }
1617
1618 /**
1619 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1620 *
1621 * @param array $options
1622 * @return array
1623 */
1624 protected function makeUpdateOptionsArray( $options ) {
1625 if ( !is_array( $options ) ) {
1626 $options = [ $options ];
1627 }
1628
1629 $opts = [];
1630
1631 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1632 $opts[] = $this->lowPriorityOption();
1633 }
1634
1635 if ( in_array( 'IGNORE', $options ) ) {
1636 $opts[] = 'IGNORE';
1637 }
1638
1639 return $opts;
1640 }
1641
1642 /**
1643 * Make UPDATE options for the DatabaseBase::update function
1644 *
1645 * @param array $options The options passed to DatabaseBase::update
1646 * @return string
1647 */
1648 protected function makeUpdateOptions( $options ) {
1649 $opts = $this->makeUpdateOptionsArray( $options );
1650
1651 return implode( ' ', $opts );
1652 }
1653
1654 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1655 $table = $this->tableName( $table );
1656 $opts = $this->makeUpdateOptions( $options );
1657 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1658
1659 if ( $conds !== [] && $conds !== '*' ) {
1660 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1661 }
1662
1663 return $this->query( $sql, $fname );
1664 }
1665
1666 public function makeList( $a, $mode = LIST_COMMA ) {
1667 if ( !is_array( $a ) ) {
1668 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1669 }
1670
1671 $first = true;
1672 $list = '';
1673
1674 foreach ( $a as $field => $value ) {
1675 if ( !$first ) {
1676 if ( $mode == LIST_AND ) {
1677 $list .= ' AND ';
1678 } elseif ( $mode == LIST_OR ) {
1679 $list .= ' OR ';
1680 } else {
1681 $list .= ',';
1682 }
1683 } else {
1684 $first = false;
1685 }
1686
1687 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1688 $list .= "($value)";
1689 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1690 $list .= "$value";
1691 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1692 // Remove null from array to be handled separately if found
1693 $includeNull = false;
1694 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1695 $includeNull = true;
1696 unset( $value[$nullKey] );
1697 }
1698 if ( count( $value ) == 0 && !$includeNull ) {
1699 throw new InvalidArgumentException( __METHOD__ . ": empty input for field $field" );
1700 } elseif ( count( $value ) == 0 ) {
1701 // only check if $field is null
1702 $list .= "$field IS NULL";
1703 } else {
1704 // IN clause contains at least one valid element
1705 if ( $includeNull ) {
1706 // Group subconditions to ensure correct precedence
1707 $list .= '(';
1708 }
1709 if ( count( $value ) == 1 ) {
1710 // Special-case single values, as IN isn't terribly efficient
1711 // Don't necessarily assume the single key is 0; we don't
1712 // enforce linear numeric ordering on other arrays here.
1713 $value = array_values( $value )[0];
1714 $list .= $field . " = " . $this->addQuotes( $value );
1715 } else {
1716 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1717 }
1718 // if null present in array, append IS NULL
1719 if ( $includeNull ) {
1720 $list .= " OR $field IS NULL)";
1721 }
1722 }
1723 } elseif ( $value === null ) {
1724 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1725 $list .= "$field IS ";
1726 } elseif ( $mode == LIST_SET ) {
1727 $list .= "$field = ";
1728 }
1729 $list .= 'NULL';
1730 } else {
1731 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1732 $list .= "$field = ";
1733 }
1734 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1735 }
1736 }
1737
1738 return $list;
1739 }
1740
1741 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1742 $conds = [];
1743
1744 foreach ( $data as $base => $sub ) {
1745 if ( count( $sub ) ) {
1746 $conds[] = $this->makeList(
1747 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1748 LIST_AND );
1749 }
1750 }
1751
1752 if ( $conds ) {
1753 return $this->makeList( $conds, LIST_OR );
1754 } else {
1755 // Nothing to search for...
1756 return false;
1757 }
1758 }
1759
1760 /**
1761 * Return aggregated value alias
1762 *
1763 * @param array $valuedata
1764 * @param string $valuename
1765 *
1766 * @return string
1767 */
1768 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1769 return $valuename;
1770 }
1771
1772 public function bitNot( $field ) {
1773 return "(~$field)";
1774 }
1775
1776 public function bitAnd( $fieldLeft, $fieldRight ) {
1777 return "($fieldLeft & $fieldRight)";
1778 }
1779
1780 public function bitOr( $fieldLeft, $fieldRight ) {
1781 return "($fieldLeft | $fieldRight)";
1782 }
1783
1784 public function buildConcat( $stringList ) {
1785 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1786 }
1787
1788 public function buildGroupConcatField(
1789 $delim, $table, $field, $conds = '', $join_conds = []
1790 ) {
1791 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1792
1793 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1794 }
1795
1796 /**
1797 * @param string $field Field or column to cast
1798 * @return string
1799 * @since 1.28
1800 */
1801 public function buildStringCast( $field ) {
1802 return $field;
1803 }
1804
1805 public function selectDB( $db ) {
1806 # Stub. Shouldn't cause serious problems if it's not overridden, but
1807 # if your database engine supports a concept similar to MySQL's
1808 # databases you may as well.
1809 $this->mDBname = $db;
1810
1811 return true;
1812 }
1813
1814 public function getDBname() {
1815 return $this->mDBname;
1816 }
1817
1818 public function getServer() {
1819 return $this->mServer;
1820 }
1821
1822 /**
1823 * Format a table name ready for use in constructing an SQL query
1824 *
1825 * This does two important things: it quotes the table names to clean them up,
1826 * and it adds a table prefix if only given a table name with no quotes.
1827 *
1828 * All functions of this object which require a table name call this function
1829 * themselves. Pass the canonical name to such functions. This is only needed
1830 * when calling query() directly.
1831 *
1832 * @note This function does not sanitize user input. It is not safe to use
1833 * this function to escape user input.
1834 * @param string $name Database table name
1835 * @param string $format One of:
1836 * quoted - Automatically pass the table name through addIdentifierQuotes()
1837 * so that it can be used in a query.
1838 * raw - Do not add identifier quotes to the table name
1839 * @return string Full database name
1840 */
1841 public function tableName( $name, $format = 'quoted' ) {
1842 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1843 # Skip the entire process when we have a string quoted on both ends.
1844 # Note that we check the end so that we will still quote any use of
1845 # use of `database`.table. But won't break things if someone wants
1846 # to query a database table with a dot in the name.
1847 if ( $this->isQuotedIdentifier( $name ) ) {
1848 return $name;
1849 }
1850
1851 # Lets test for any bits of text that should never show up in a table
1852 # name. Basically anything like JOIN or ON which are actually part of
1853 # SQL queries, but may end up inside of the table value to combine
1854 # sql. Such as how the API is doing.
1855 # Note that we use a whitespace test rather than a \b test to avoid
1856 # any remote case where a word like on may be inside of a table name
1857 # surrounded by symbols which may be considered word breaks.
1858 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1859 return $name;
1860 }
1861
1862 # Split database and table into proper variables.
1863 # We reverse the explode so that database.table and table both output
1864 # the correct table.
1865 $dbDetails = explode( '.', $name, 3 );
1866 if ( count( $dbDetails ) == 3 ) {
1867 list( $database, $schema, $table ) = $dbDetails;
1868 # We don't want any prefix added in this case
1869 $prefix = '';
1870 } elseif ( count( $dbDetails ) == 2 ) {
1871 list( $database, $table ) = $dbDetails;
1872 # We don't want any prefix added in this case
1873 # In dbs that support it, $database may actually be the schema
1874 # but that doesn't affect any of the functionality here
1875 $prefix = '';
1876 $schema = null;
1877 } else {
1878 list( $table ) = $dbDetails;
1879 if ( $wgSharedDB !== null # We have a shared database
1880 && $this->mForeign == false # We're not working on a foreign database
1881 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1882 && in_array( $table, $wgSharedTables ) # A shared table is selected
1883 ) {
1884 $database = $wgSharedDB;
1885 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
1886 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
1887 } else {
1888 $database = null;
1889 $schema = $this->mSchema; # Default schema
1890 $prefix = $this->mTablePrefix; # Default prefix
1891 }
1892 }
1893
1894 # Quote $table and apply the prefix if not quoted.
1895 # $tableName might be empty if this is called from Database::replaceVars()
1896 $tableName = "{$prefix}{$table}";
1897 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1898 $tableName = $this->addIdentifierQuotes( $tableName );
1899 }
1900
1901 # Quote $schema and merge it with the table name if needed
1902 if ( strlen( $schema ) ) {
1903 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1904 $schema = $this->addIdentifierQuotes( $schema );
1905 }
1906 $tableName = $schema . '.' . $tableName;
1907 }
1908
1909 # Quote $database and merge it with the table name if needed
1910 if ( $database !== null ) {
1911 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1912 $database = $this->addIdentifierQuotes( $database );
1913 }
1914 $tableName = $database . '.' . $tableName;
1915 }
1916
1917 return $tableName;
1918 }
1919
1920 /**
1921 * Fetch a number of table names into an array
1922 * This is handy when you need to construct SQL for joins
1923 *
1924 * Example:
1925 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1926 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1927 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1928 *
1929 * @return array
1930 */
1931 public function tableNames() {
1932 $inArray = func_get_args();
1933 $retVal = [];
1934
1935 foreach ( $inArray as $name ) {
1936 $retVal[$name] = $this->tableName( $name );
1937 }
1938
1939 return $retVal;
1940 }
1941
1942 /**
1943 * Fetch a number of table names into an zero-indexed numerical array
1944 * This is handy when you need to construct SQL for joins
1945 *
1946 * Example:
1947 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1948 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1949 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1950 *
1951 * @return array
1952 */
1953 public function tableNamesN() {
1954 $inArray = func_get_args();
1955 $retVal = [];
1956
1957 foreach ( $inArray as $name ) {
1958 $retVal[] = $this->tableName( $name );
1959 }
1960
1961 return $retVal;
1962 }
1963
1964 /**
1965 * Get an aliased table name
1966 * e.g. tableName AS newTableName
1967 *
1968 * @param string $name Table name, see tableName()
1969 * @param string|bool $alias Alias (optional)
1970 * @return string SQL name for aliased table. Will not alias a table to its own name
1971 */
1972 public function tableNameWithAlias( $name, $alias = false ) {
1973 if ( !$alias || $alias == $name ) {
1974 return $this->tableName( $name );
1975 } else {
1976 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1977 }
1978 }
1979
1980 /**
1981 * Gets an array of aliased table names
1982 *
1983 * @param array $tables [ [alias] => table ]
1984 * @return string[] See tableNameWithAlias()
1985 */
1986 public function tableNamesWithAlias( $tables ) {
1987 $retval = [];
1988 foreach ( $tables as $alias => $table ) {
1989 if ( is_numeric( $alias ) ) {
1990 $alias = $table;
1991 }
1992 $retval[] = $this->tableNameWithAlias( $table, $alias );
1993 }
1994
1995 return $retval;
1996 }
1997
1998 /**
1999 * Get an aliased field name
2000 * e.g. fieldName AS newFieldName
2001 *
2002 * @param string $name Field name
2003 * @param string|bool $alias Alias (optional)
2004 * @return string SQL name for aliased field. Will not alias a field to its own name
2005 */
2006 public function fieldNameWithAlias( $name, $alias = false ) {
2007 if ( !$alias || (string)$alias === (string)$name ) {
2008 return $name;
2009 } else {
2010 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2011 }
2012 }
2013
2014 /**
2015 * Gets an array of aliased field names
2016 *
2017 * @param array $fields [ [alias] => field ]
2018 * @return string[] See fieldNameWithAlias()
2019 */
2020 public function fieldNamesWithAlias( $fields ) {
2021 $retval = [];
2022 foreach ( $fields as $alias => $field ) {
2023 if ( is_numeric( $alias ) ) {
2024 $alias = $field;
2025 }
2026 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2027 }
2028
2029 return $retval;
2030 }
2031
2032 /**
2033 * Get the aliased table name clause for a FROM clause
2034 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2035 *
2036 * @param array $tables ( [alias] => table )
2037 * @param array $use_index Same as for select()
2038 * @param array $ignore_index Same as for select()
2039 * @param array $join_conds Same as for select()
2040 * @return string
2041 */
2042 protected function tableNamesWithIndexClauseOrJOIN(
2043 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2044 ) {
2045 $ret = [];
2046 $retJOIN = [];
2047 $use_index = (array)$use_index;
2048 $ignore_index = (array)$ignore_index;
2049 $join_conds = (array)$join_conds;
2050
2051 foreach ( $tables as $alias => $table ) {
2052 if ( !is_string( $alias ) ) {
2053 // No alias? Set it equal to the table name
2054 $alias = $table;
2055 }
2056 // Is there a JOIN clause for this table?
2057 if ( isset( $join_conds[$alias] ) ) {
2058 list( $joinType, $conds ) = $join_conds[$alias];
2059 $tableClause = $joinType;
2060 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2061 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2062 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2063 if ( $use != '' ) {
2064 $tableClause .= ' ' . $use;
2065 }
2066 }
2067 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2068 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2069 if ( $ignore != '' ) {
2070 $tableClause .= ' ' . $ignore;
2071 }
2072 }
2073 $on = $this->makeList( (array)$conds, LIST_AND );
2074 if ( $on != '' ) {
2075 $tableClause .= ' ON (' . $on . ')';
2076 }
2077
2078 $retJOIN[] = $tableClause;
2079 } elseif ( isset( $use_index[$alias] ) ) {
2080 // Is there an INDEX clause for this table?
2081 $tableClause = $this->tableNameWithAlias( $table, $alias );
2082 $tableClause .= ' ' . $this->useIndexClause(
2083 implode( ',', (array)$use_index[$alias] )
2084 );
2085
2086 $ret[] = $tableClause;
2087 } elseif ( isset( $ignore_index[$alias] ) ) {
2088 // Is there an INDEX clause for this table?
2089 $tableClause = $this->tableNameWithAlias( $table, $alias );
2090 $tableClause .= ' ' . $this->ignoreIndexClause(
2091 implode( ',', (array)$ignore_index[$alias] )
2092 );
2093
2094 $ret[] = $tableClause;
2095 } else {
2096 $tableClause = $this->tableNameWithAlias( $table, $alias );
2097
2098 $ret[] = $tableClause;
2099 }
2100 }
2101
2102 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2103 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2104 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2105
2106 // Compile our final table clause
2107 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2108 }
2109
2110 /**
2111 * Get the name of an index in a given table.
2112 *
2113 * @param string $index
2114 * @return string
2115 */
2116 protected function indexName( $index ) {
2117 // Backwards-compatibility hack
2118 $renamed = [
2119 'ar_usertext_timestamp' => 'usertext_timestamp',
2120 'un_user_id' => 'user_id',
2121 'un_user_ip' => 'user_ip',
2122 ];
2123
2124 if ( isset( $renamed[$index] ) ) {
2125 return $renamed[$index];
2126 } else {
2127 return $index;
2128 }
2129 }
2130
2131 public function addQuotes( $s ) {
2132 if ( $s instanceof Blob ) {
2133 $s = $s->fetch();
2134 }
2135 if ( $s === null ) {
2136 return 'NULL';
2137 } else {
2138 # This will also quote numeric values. This should be harmless,
2139 # and protects against weird problems that occur when they really
2140 # _are_ strings such as article titles and string->number->string
2141 # conversion is not 1:1.
2142 return "'" . $this->strencode( $s ) . "'";
2143 }
2144 }
2145
2146 /**
2147 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2148 * MySQL uses `backticks` while basically everything else uses double quotes.
2149 * Since MySQL is the odd one out here the double quotes are our generic
2150 * and we implement backticks in DatabaseMysql.
2151 *
2152 * @param string $s
2153 * @return string
2154 */
2155 public function addIdentifierQuotes( $s ) {
2156 return '"' . str_replace( '"', '""', $s ) . '"';
2157 }
2158
2159 /**
2160 * Returns if the given identifier looks quoted or not according to
2161 * the database convention for quoting identifiers .
2162 *
2163 * @note Do not use this to determine if untrusted input is safe.
2164 * A malicious user can trick this function.
2165 * @param string $name
2166 * @return bool
2167 */
2168 public function isQuotedIdentifier( $name ) {
2169 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2170 }
2171
2172 /**
2173 * @param string $s
2174 * @return string
2175 */
2176 protected function escapeLikeInternal( $s ) {
2177 return addcslashes( $s, '\%_' );
2178 }
2179
2180 public function buildLike() {
2181 $params = func_get_args();
2182
2183 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2184 $params = $params[0];
2185 }
2186
2187 $s = '';
2188
2189 foreach ( $params as $value ) {
2190 if ( $value instanceof LikeMatch ) {
2191 $s .= $value->toString();
2192 } else {
2193 $s .= $this->escapeLikeInternal( $value );
2194 }
2195 }
2196
2197 return " LIKE {$this->addQuotes( $s )} ";
2198 }
2199
2200 public function anyChar() {
2201 return new LikeMatch( '_' );
2202 }
2203
2204 public function anyString() {
2205 return new LikeMatch( '%' );
2206 }
2207
2208 public function nextSequenceValue( $seqName ) {
2209 return null;
2210 }
2211
2212 /**
2213 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2214 * is only needed because a) MySQL must be as efficient as possible due to
2215 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2216 * which index to pick. Anyway, other databases might have different
2217 * indexes on a given table. So don't bother overriding this unless you're
2218 * MySQL.
2219 * @param string $index
2220 * @return string
2221 */
2222 public function useIndexClause( $index ) {
2223 return '';
2224 }
2225
2226 /**
2227 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2228 * is only needed because a) MySQL must be as efficient as possible due to
2229 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2230 * which index to pick. Anyway, other databases might have different
2231 * indexes on a given table. So don't bother overriding this unless you're
2232 * MySQL.
2233 * @param string $index
2234 * @return string
2235 */
2236 public function ignoreIndexClause( $index ) {
2237 return '';
2238 }
2239
2240 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2241 $quotedTable = $this->tableName( $table );
2242
2243 if ( count( $rows ) == 0 ) {
2244 return;
2245 }
2246
2247 # Single row case
2248 if ( !is_array( reset( $rows ) ) ) {
2249 $rows = [ $rows ];
2250 }
2251
2252 // @FXIME: this is not atomic, but a trx would break affectedRows()
2253 foreach ( $rows as $row ) {
2254 # Delete rows which collide
2255 if ( $uniqueIndexes ) {
2256 $sql = "DELETE FROM $quotedTable WHERE ";
2257 $first = true;
2258 foreach ( $uniqueIndexes as $index ) {
2259 if ( $first ) {
2260 $first = false;
2261 $sql .= '( ';
2262 } else {
2263 $sql .= ' ) OR ( ';
2264 }
2265 if ( is_array( $index ) ) {
2266 $first2 = true;
2267 foreach ( $index as $col ) {
2268 if ( $first2 ) {
2269 $first2 = false;
2270 } else {
2271 $sql .= ' AND ';
2272 }
2273 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2274 }
2275 } else {
2276 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2277 }
2278 }
2279 $sql .= ' )';
2280 $this->query( $sql, $fname );
2281 }
2282
2283 # Now insert the row
2284 $this->insert( $table, $row, $fname );
2285 }
2286 }
2287
2288 /**
2289 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2290 * statement.
2291 *
2292 * @param string $table Table name
2293 * @param array|string $rows Row(s) to insert
2294 * @param string $fname Caller function name
2295 *
2296 * @return ResultWrapper
2297 */
2298 protected function nativeReplace( $table, $rows, $fname ) {
2299 $table = $this->tableName( $table );
2300
2301 # Single row case
2302 if ( !is_array( reset( $rows ) ) ) {
2303 $rows = [ $rows ];
2304 }
2305
2306 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2307 $first = true;
2308
2309 foreach ( $rows as $row ) {
2310 if ( $first ) {
2311 $first = false;
2312 } else {
2313 $sql .= ',';
2314 }
2315
2316 $sql .= '(' . $this->makeList( $row ) . ')';
2317 }
2318
2319 return $this->query( $sql, $fname );
2320 }
2321
2322 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2323 $fname = __METHOD__
2324 ) {
2325 if ( !count( $rows ) ) {
2326 return true; // nothing to do
2327 }
2328
2329 if ( !is_array( reset( $rows ) ) ) {
2330 $rows = [ $rows ];
2331 }
2332
2333 if ( count( $uniqueIndexes ) ) {
2334 $clauses = []; // list WHERE clauses that each identify a single row
2335 foreach ( $rows as $row ) {
2336 foreach ( $uniqueIndexes as $index ) {
2337 $index = is_array( $index ) ? $index : [ $index ]; // columns
2338 $rowKey = []; // unique key to this row
2339 foreach ( $index as $column ) {
2340 $rowKey[$column] = $row[$column];
2341 }
2342 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2343 }
2344 }
2345 $where = [ $this->makeList( $clauses, LIST_OR ) ];
2346 } else {
2347 $where = false;
2348 }
2349
2350 $useTrx = !$this->mTrxLevel;
2351 if ( $useTrx ) {
2352 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2353 }
2354 try {
2355 # Update any existing conflicting row(s)
2356 if ( $where !== false ) {
2357 $ok = $this->update( $table, $set, $where, $fname );
2358 } else {
2359 $ok = true;
2360 }
2361 # Now insert any non-conflicting row(s)
2362 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2363 } catch ( Exception $e ) {
2364 if ( $useTrx ) {
2365 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2366 }
2367 throw $e;
2368 }
2369 if ( $useTrx ) {
2370 $this->commit( $fname, self::FLUSHING_INTERNAL );
2371 }
2372
2373 return $ok;
2374 }
2375
2376 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2377 $fname = __METHOD__
2378 ) {
2379 if ( !$conds ) {
2380 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2381 }
2382
2383 $delTable = $this->tableName( $delTable );
2384 $joinTable = $this->tableName( $joinTable );
2385 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2386 if ( $conds != '*' ) {
2387 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2388 }
2389 $sql .= ')';
2390
2391 $this->query( $sql, $fname );
2392 }
2393
2394 /**
2395 * Returns the size of a text field, or -1 for "unlimited"
2396 *
2397 * @param string $table
2398 * @param string $field
2399 * @return int
2400 */
2401 public function textFieldSize( $table, $field ) {
2402 $table = $this->tableName( $table );
2403 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2404 $res = $this->query( $sql, __METHOD__ );
2405 $row = $this->fetchObject( $res );
2406
2407 $m = [];
2408
2409 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2410 $size = $m[1];
2411 } else {
2412 $size = -1;
2413 }
2414
2415 return $size;
2416 }
2417
2418 /**
2419 * A string to insert into queries to show that they're low-priority, like
2420 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2421 * string and nothing bad should happen.
2422 *
2423 * @return string Returns the text of the low priority option if it is
2424 * supported, or a blank string otherwise
2425 */
2426 public function lowPriorityOption() {
2427 return '';
2428 }
2429
2430 public function delete( $table, $conds, $fname = __METHOD__ ) {
2431 if ( !$conds ) {
2432 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2433 }
2434
2435 $table = $this->tableName( $table );
2436 $sql = "DELETE FROM $table";
2437
2438 if ( $conds != '*' ) {
2439 if ( is_array( $conds ) ) {
2440 $conds = $this->makeList( $conds, LIST_AND );
2441 }
2442 $sql .= ' WHERE ' . $conds;
2443 }
2444
2445 return $this->query( $sql, $fname );
2446 }
2447
2448 public function insertSelect(
2449 $destTable, $srcTable, $varMap, $conds,
2450 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2451 ) {
2452 if ( $this->cliMode ) {
2453 // For massive migrations with downtime, we don't want to select everything
2454 // into memory and OOM, so do all this native on the server side if possible.
2455 return $this->nativeInsertSelect(
2456 $destTable,
2457 $srcTable,
2458 $varMap,
2459 $conds,
2460 $fname,
2461 $insertOptions,
2462 $selectOptions
2463 );
2464 }
2465
2466 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2467 // on only the master (without needing row-based-replication). It also makes it easy to
2468 // know how big the INSERT is going to be.
2469 $fields = [];
2470 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2471 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2472 }
2473 $selectOptions[] = 'FOR UPDATE';
2474 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2475 if ( !$res ) {
2476 return false;
2477 }
2478
2479 $rows = [];
2480 foreach ( $res as $row ) {
2481 $rows[] = (array)$row;
2482 }
2483
2484 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2485 }
2486
2487 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2488 $fname = __METHOD__,
2489 $insertOptions = [], $selectOptions = []
2490 ) {
2491 $destTable = $this->tableName( $destTable );
2492
2493 if ( !is_array( $insertOptions ) ) {
2494 $insertOptions = [ $insertOptions ];
2495 }
2496
2497 $insertOptions = $this->makeInsertOptions( $insertOptions );
2498
2499 if ( !is_array( $selectOptions ) ) {
2500 $selectOptions = [ $selectOptions ];
2501 }
2502
2503 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2504 $selectOptions );
2505
2506 if ( is_array( $srcTable ) ) {
2507 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2508 } else {
2509 $srcTable = $this->tableName( $srcTable );
2510 }
2511
2512 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2513 " SELECT $startOpts " . implode( ',', $varMap ) .
2514 " FROM $srcTable $useIndex $ignoreIndex ";
2515
2516 if ( $conds != '*' ) {
2517 if ( is_array( $conds ) ) {
2518 $conds = $this->makeList( $conds, LIST_AND );
2519 }
2520 $sql .= " WHERE $conds";
2521 }
2522
2523 $sql .= " $tailOpts";
2524
2525 return $this->query( $sql, $fname );
2526 }
2527
2528 /**
2529 * Construct a LIMIT query with optional offset. This is used for query
2530 * pages. The SQL should be adjusted so that only the first $limit rows
2531 * are returned. If $offset is provided as well, then the first $offset
2532 * rows should be discarded, and the next $limit rows should be returned.
2533 * If the result of the query is not ordered, then the rows to be returned
2534 * are theoretically arbitrary.
2535 *
2536 * $sql is expected to be a SELECT, if that makes a difference.
2537 *
2538 * The version provided by default works in MySQL and SQLite. It will very
2539 * likely need to be overridden for most other DBMSes.
2540 *
2541 * @param string $sql SQL query we will append the limit too
2542 * @param int $limit The SQL limit
2543 * @param int|bool $offset The SQL offset (default false)
2544 * @throws DBUnexpectedError
2545 * @return string
2546 */
2547 public function limitResult( $sql, $limit, $offset = false ) {
2548 if ( !is_numeric( $limit ) ) {
2549 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2550 }
2551
2552 return "$sql LIMIT "
2553 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2554 . "{$limit} ";
2555 }
2556
2557 public function unionSupportsOrderAndLimit() {
2558 return true; // True for almost every DB supported
2559 }
2560
2561 public function unionQueries( $sqls, $all ) {
2562 $glue = $all ? ') UNION ALL (' : ') UNION (';
2563
2564 return '(' . implode( $glue, $sqls ) . ')';
2565 }
2566
2567 public function conditional( $cond, $trueVal, $falseVal ) {
2568 if ( is_array( $cond ) ) {
2569 $cond = $this->makeList( $cond, LIST_AND );
2570 }
2571
2572 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2573 }
2574
2575 public function strreplace( $orig, $old, $new ) {
2576 return "REPLACE({$orig}, {$old}, {$new})";
2577 }
2578
2579 public function getServerUptime() {
2580 return 0;
2581 }
2582
2583 public function wasDeadlock() {
2584 return false;
2585 }
2586
2587 public function wasLockTimeout() {
2588 return false;
2589 }
2590
2591 public function wasErrorReissuable() {
2592 return false;
2593 }
2594
2595 public function wasReadOnlyError() {
2596 return false;
2597 }
2598
2599 /**
2600 * Determines if the given query error was a connection drop
2601 * STUB
2602 *
2603 * @param integer|string $errno
2604 * @return bool
2605 */
2606 public function wasConnectionError( $errno ) {
2607 return false;
2608 }
2609
2610 /**
2611 * Perform a deadlock-prone transaction.
2612 *
2613 * This function invokes a callback function to perform a set of write
2614 * queries. If a deadlock occurs during the processing, the transaction
2615 * will be rolled back and the callback function will be called again.
2616 *
2617 * Avoid using this method outside of Job or Maintenance classes.
2618 *
2619 * Usage:
2620 * $dbw->deadlockLoop( callback, ... );
2621 *
2622 * Extra arguments are passed through to the specified callback function.
2623 * This method requires that no transactions are already active to avoid
2624 * causing premature commits or exceptions.
2625 *
2626 * Returns whatever the callback function returned on its successful,
2627 * iteration, or false on error, for example if the retry limit was
2628 * reached.
2629 *
2630 * @return mixed
2631 * @throws DBUnexpectedError
2632 * @throws Exception
2633 */
2634 public function deadlockLoop() {
2635 $args = func_get_args();
2636 $function = array_shift( $args );
2637 $tries = self::DEADLOCK_TRIES;
2638
2639 $this->begin( __METHOD__ );
2640
2641 $retVal = null;
2642 /** @var Exception $e */
2643 $e = null;
2644 do {
2645 try {
2646 $retVal = call_user_func_array( $function, $args );
2647 break;
2648 } catch ( DBQueryError $e ) {
2649 if ( $this->wasDeadlock() ) {
2650 // Retry after a randomized delay
2651 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2652 } else {
2653 // Throw the error back up
2654 throw $e;
2655 }
2656 }
2657 } while ( --$tries > 0 );
2658
2659 if ( $tries <= 0 ) {
2660 // Too many deadlocks; give up
2661 $this->rollback( __METHOD__ );
2662 throw $e;
2663 } else {
2664 $this->commit( __METHOD__ );
2665
2666 return $retVal;
2667 }
2668 }
2669
2670 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2671 # Real waits are implemented in the subclass.
2672 return 0;
2673 }
2674
2675 public function getSlavePos() {
2676 # Stub
2677 return false;
2678 }
2679
2680 public function getMasterPos() {
2681 # Stub
2682 return false;
2683 }
2684
2685 public function serverIsReadOnly() {
2686 return false;
2687 }
2688
2689 final public function onTransactionResolution( callable $callback ) {
2690 if ( !$this->mTrxLevel ) {
2691 throw new DBUnexpectedError( $this, "No transaction is active." );
2692 }
2693 $this->mTrxEndCallbacks[] = [ $callback, wfGetCaller() ];
2694 }
2695
2696 final public function onTransactionIdle( callable $callback ) {
2697 $this->mTrxIdleCallbacks[] = [ $callback, wfGetCaller() ];
2698 if ( !$this->mTrxLevel ) {
2699 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2700 }
2701 }
2702
2703 final public function onTransactionPreCommitOrIdle( callable $callback ) {
2704 if ( $this->mTrxLevel ) {
2705 $this->mTrxPreCommitCallbacks[] = [ $callback, wfGetCaller() ];
2706 } else {
2707 // If no transaction is active, then make one for this callback
2708 $this->startAtomic( __METHOD__ );
2709 try {
2710 call_user_func( $callback );
2711 $this->endAtomic( __METHOD__ );
2712 } catch ( Exception $e ) {
2713 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2714 throw $e;
2715 }
2716 }
2717 }
2718
2719 final public function setTransactionListener( $name, callable $callback = null ) {
2720 if ( $callback ) {
2721 $this->mTrxRecurringCallbacks[$name] = [ $callback, wfGetCaller() ];
2722 } else {
2723 unset( $this->mTrxRecurringCallbacks[$name] );
2724 }
2725 }
2726
2727 /**
2728 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2729 *
2730 * This method should not be used outside of Database/LoadBalancer
2731 *
2732 * @param bool $suppress
2733 * @since 1.28
2734 */
2735 final public function setTrxEndCallbackSuppression( $suppress ) {
2736 $this->mTrxEndCallbacksSuppressed = $suppress;
2737 }
2738
2739 /**
2740 * Actually run and consume any "on transaction idle/resolution" callbacks.
2741 *
2742 * This method should not be used outside of Database/LoadBalancer
2743 *
2744 * @param integer $trigger IDatabase::TRIGGER_* constant
2745 * @since 1.20
2746 * @throws Exception
2747 */
2748 public function runOnTransactionIdleCallbacks( $trigger ) {
2749 if ( $this->mTrxEndCallbacksSuppressed ) {
2750 return;
2751 }
2752
2753 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
2754 /** @var Exception $e */
2755 $e = null; // first exception
2756 do { // callbacks may add callbacks :)
2757 $callbacks = array_merge(
2758 $this->mTrxIdleCallbacks,
2759 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2760 );
2761 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2762 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2763 foreach ( $callbacks as $callback ) {
2764 try {
2765 list( $phpCallback ) = $callback;
2766 $this->clearFlag( DBO_TRX ); // make each query its own transaction
2767 call_user_func_array( $phpCallback, [ $trigger ] );
2768 if ( $autoTrx ) {
2769 $this->setFlag( DBO_TRX ); // restore automatic begin()
2770 } else {
2771 $this->clearFlag( DBO_TRX ); // restore auto-commit
2772 }
2773 } catch ( Exception $ex ) {
2774 call_user_func( $this->errorLogger, $ex );
2775 $e = $e ?: $ex;
2776 // Some callbacks may use startAtomic/endAtomic, so make sure
2777 // their transactions are ended so other callbacks don't fail
2778 if ( $this->trxLevel() ) {
2779 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2780 }
2781 }
2782 }
2783 } while ( count( $this->mTrxIdleCallbacks ) );
2784
2785 if ( $e instanceof Exception ) {
2786 throw $e; // re-throw any first exception
2787 }
2788 }
2789
2790 /**
2791 * Actually run and consume any "on transaction pre-commit" callbacks.
2792 *
2793 * This method should not be used outside of Database/LoadBalancer
2794 *
2795 * @since 1.22
2796 * @throws Exception
2797 */
2798 public function runOnTransactionPreCommitCallbacks() {
2799 $e = null; // first exception
2800 do { // callbacks may add callbacks :)
2801 $callbacks = $this->mTrxPreCommitCallbacks;
2802 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2803 foreach ( $callbacks as $callback ) {
2804 try {
2805 list( $phpCallback ) = $callback;
2806 call_user_func( $phpCallback );
2807 } catch ( Exception $ex ) {
2808 call_user_func( $this->errorLogger, $ex );
2809 $e = $e ?: $ex;
2810 }
2811 }
2812 } while ( count( $this->mTrxPreCommitCallbacks ) );
2813
2814 if ( $e instanceof Exception ) {
2815 throw $e; // re-throw any first exception
2816 }
2817 }
2818
2819 /**
2820 * Actually run any "transaction listener" callbacks.
2821 *
2822 * This method should not be used outside of Database/LoadBalancer
2823 *
2824 * @param integer $trigger IDatabase::TRIGGER_* constant
2825 * @throws Exception
2826 * @since 1.20
2827 */
2828 public function runTransactionListenerCallbacks( $trigger ) {
2829 if ( $this->mTrxEndCallbacksSuppressed ) {
2830 return;
2831 }
2832
2833 /** @var Exception $e */
2834 $e = null; // first exception
2835
2836 foreach ( $this->mTrxRecurringCallbacks as $callback ) {
2837 try {
2838 list( $phpCallback ) = $callback;
2839 $phpCallback( $trigger, $this );
2840 } catch ( Exception $ex ) {
2841 call_user_func( $this->errorLogger, $ex );
2842 $e = $e ?: $ex;
2843 }
2844 }
2845
2846 if ( $e instanceof Exception ) {
2847 throw $e; // re-throw any first exception
2848 }
2849 }
2850
2851 final public function startAtomic( $fname = __METHOD__ ) {
2852 if ( !$this->mTrxLevel ) {
2853 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2854 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2855 // in all changes being in one transaction to keep requests transactional.
2856 if ( !$this->getFlag( DBO_TRX ) ) {
2857 $this->mTrxAutomaticAtomic = true;
2858 }
2859 }
2860
2861 $this->mTrxAtomicLevels[] = $fname;
2862 }
2863
2864 final public function endAtomic( $fname = __METHOD__ ) {
2865 if ( !$this->mTrxLevel ) {
2866 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2867 }
2868 if ( !$this->mTrxAtomicLevels ||
2869 array_pop( $this->mTrxAtomicLevels ) !== $fname
2870 ) {
2871 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2872 }
2873
2874 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2875 $this->commit( $fname, self::FLUSHING_INTERNAL );
2876 }
2877 }
2878
2879 final public function doAtomicSection( $fname, callable $callback ) {
2880 $this->startAtomic( $fname );
2881 try {
2882 $res = call_user_func_array( $callback, [ $this, $fname ] );
2883 } catch ( Exception $e ) {
2884 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2885 throw $e;
2886 }
2887 $this->endAtomic( $fname );
2888
2889 return $res;
2890 }
2891
2892 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2893 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2894 if ( $this->mTrxLevel ) {
2895 if ( $this->mTrxAtomicLevels ) {
2896 $levels = implode( ', ', $this->mTrxAtomicLevels );
2897 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2898 throw new DBUnexpectedError( $this, $msg );
2899 } elseif ( !$this->mTrxAutomatic ) {
2900 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2901 throw new DBUnexpectedError( $this, $msg );
2902 } else {
2903 // @TODO: make this an exception at some point
2904 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2905 $this->queryLogger->error( $msg );
2906 return; // join the main transaction set
2907 }
2908 } elseif ( $this->getFlag( DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2909 // @TODO: make this an exception at some point
2910 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2911 $this->queryLogger->error( $msg );
2912 return; // let any writes be in the main transaction
2913 }
2914
2915 // Avoid fatals if close() was called
2916 $this->assertOpen();
2917
2918 $this->doBegin( $fname );
2919 $this->mTrxTimestamp = microtime( true );
2920 $this->mTrxFname = $fname;
2921 $this->mTrxDoneWrites = false;
2922 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2923 $this->mTrxAutomaticAtomic = false;
2924 $this->mTrxAtomicLevels = [];
2925 $this->mTrxShortId = wfRandomString( 12 );
2926 $this->mTrxWriteDuration = 0.0;
2927 $this->mTrxWriteQueryCount = 0;
2928 $this->mTrxWriteAdjDuration = 0.0;
2929 $this->mTrxWriteAdjQueryCount = 0;
2930 $this->mTrxWriteCallers = [];
2931 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2932 // Get an estimate of the replica DB lag before then, treating estimate staleness
2933 // as lag itself just to be safe
2934 $status = $this->getApproximateLagStatus();
2935 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2936 }
2937
2938 /**
2939 * Issues the BEGIN command to the database server.
2940 *
2941 * @see DatabaseBase::begin()
2942 * @param string $fname
2943 */
2944 protected function doBegin( $fname ) {
2945 $this->query( 'BEGIN', $fname );
2946 $this->mTrxLevel = 1;
2947 }
2948
2949 final public function commit( $fname = __METHOD__, $flush = '' ) {
2950 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2951 // There are still atomic sections open. This cannot be ignored
2952 $levels = implode( ', ', $this->mTrxAtomicLevels );
2953 throw new DBUnexpectedError(
2954 $this,
2955 "$fname: Got COMMIT while atomic sections $levels are still open."
2956 );
2957 }
2958
2959 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2960 if ( !$this->mTrxLevel ) {
2961 return; // nothing to do
2962 } elseif ( !$this->mTrxAutomatic ) {
2963 throw new DBUnexpectedError(
2964 $this,
2965 "$fname: Flushing an explicit transaction, getting out of sync."
2966 );
2967 }
2968 } else {
2969 if ( !$this->mTrxLevel ) {
2970 $this->queryLogger->error( "$fname: No transaction to commit, something got out of sync." );
2971 return; // nothing to do
2972 } elseif ( $this->mTrxAutomatic ) {
2973 // @TODO: make this an exception at some point
2974 $msg = "$fname: Explicit commit of implicit transaction.";
2975 $this->queryLogger->error( $msg );
2976 return; // wait for the main transaction set commit round
2977 }
2978 }
2979
2980 // Avoid fatals if close() was called
2981 $this->assertOpen();
2982
2983 $this->runOnTransactionPreCommitCallbacks();
2984 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2985 $this->doCommit( $fname );
2986 if ( $this->mTrxDoneWrites ) {
2987 $this->mDoneWrites = microtime( true );
2988 $this->trxProfiler->transactionWritingOut(
2989 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2990 }
2991
2992 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2993 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2994 }
2995
2996 /**
2997 * Issues the COMMIT command to the database server.
2998 *
2999 * @see DatabaseBase::commit()
3000 * @param string $fname
3001 */
3002 protected function doCommit( $fname ) {
3003 if ( $this->mTrxLevel ) {
3004 $this->query( 'COMMIT', $fname );
3005 $this->mTrxLevel = 0;
3006 }
3007 }
3008
3009 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3010 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3011 if ( !$this->mTrxLevel ) {
3012 return; // nothing to do
3013 }
3014 } else {
3015 if ( !$this->mTrxLevel ) {
3016 $this->queryLogger->error(
3017 "$fname: No transaction to rollback, something got out of sync." );
3018 return; // nothing to do
3019 } elseif ( $this->getFlag( DBO_TRX ) ) {
3020 throw new DBUnexpectedError(
3021 $this,
3022 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3023 );
3024 }
3025 }
3026
3027 // Avoid fatals if close() was called
3028 $this->assertOpen();
3029
3030 $this->doRollback( $fname );
3031 $this->mTrxAtomicLevels = [];
3032 if ( $this->mTrxDoneWrites ) {
3033 $this->trxProfiler->transactionWritingOut(
3034 $this->mServer, $this->mDBname, $this->mTrxShortId );
3035 }
3036
3037 $this->mTrxIdleCallbacks = []; // clear
3038 $this->mTrxPreCommitCallbacks = []; // clear
3039 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3040 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3041 }
3042
3043 /**
3044 * Issues the ROLLBACK command to the database server.
3045 *
3046 * @see DatabaseBase::rollback()
3047 * @param string $fname
3048 */
3049 protected function doRollback( $fname ) {
3050 if ( $this->mTrxLevel ) {
3051 # Disconnects cause rollback anyway, so ignore those errors
3052 $ignoreErrors = true;
3053 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3054 $this->mTrxLevel = 0;
3055 }
3056 }
3057
3058 public function flushSnapshot( $fname = __METHOD__ ) {
3059 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3060 // This only flushes transactions to clear snapshots, not to write data
3061 throw new DBUnexpectedError(
3062 $this,
3063 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3064 );
3065 }
3066
3067 $this->commit( $fname, self::FLUSHING_INTERNAL );
3068 }
3069
3070 public function explicitTrxActive() {
3071 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
3072 }
3073
3074 /**
3075 * Creates a new table with structure copied from existing table
3076 * Note that unlike most database abstraction functions, this function does not
3077 * automatically append database prefix, because it works at a lower
3078 * abstraction level.
3079 * The table names passed to this function shall not be quoted (this
3080 * function calls addIdentifierQuotes when needed).
3081 *
3082 * @param string $oldName Name of table whose structure should be copied
3083 * @param string $newName Name of table to be created
3084 * @param bool $temporary Whether the new table should be temporary
3085 * @param string $fname Calling function name
3086 * @throws RuntimeException
3087 * @return bool True if operation was successful
3088 */
3089 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3090 $fname = __METHOD__
3091 ) {
3092 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3093 }
3094
3095 function listTables( $prefix = null, $fname = __METHOD__ ) {
3096 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3097 }
3098
3099 /**
3100 * Reset the views process cache set by listViews()
3101 * @since 1.22
3102 */
3103 final public function clearViewsCache() {
3104 $this->allViews = null;
3105 }
3106
3107 /**
3108 * Lists all the VIEWs in the database
3109 *
3110 * For caching purposes the list of all views should be stored in
3111 * $this->allViews. The process cache can be cleared with clearViewsCache()
3112 *
3113 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3114 * @param string $fname Name of calling function
3115 * @throws RuntimeException
3116 * @return array
3117 * @since 1.22
3118 */
3119 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3120 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3121 }
3122
3123 /**
3124 * Differentiates between a TABLE and a VIEW
3125 *
3126 * @param string $name Name of the database-structure to test.
3127 * @throws RuntimeException
3128 * @return bool
3129 * @since 1.22
3130 */
3131 public function isView( $name ) {
3132 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3133 }
3134
3135 public function timestamp( $ts = 0 ) {
3136 return wfTimestamp( TS_MW, $ts );
3137 }
3138
3139 public function timestampOrNull( $ts = null ) {
3140 if ( is_null( $ts ) ) {
3141 return null;
3142 } else {
3143 return $this->timestamp( $ts );
3144 }
3145 }
3146
3147 /**
3148 * Take the result from a query, and wrap it in a ResultWrapper if
3149 * necessary. Boolean values are passed through as is, to indicate success
3150 * of write queries or failure.
3151 *
3152 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3153 * resource, and it was necessary to call this function to convert it to
3154 * a wrapper. Nowadays, raw database objects are never exposed to external
3155 * callers, so this is unnecessary in external code.
3156 *
3157 * @param bool|ResultWrapper|resource|object $result
3158 * @return bool|ResultWrapper
3159 */
3160 protected function resultObject( $result ) {
3161 if ( !$result ) {
3162 return false;
3163 } elseif ( $result instanceof ResultWrapper ) {
3164 return $result;
3165 } elseif ( $result === true ) {
3166 // Successful write query
3167 return $result;
3168 } else {
3169 return new ResultWrapper( $this, $result );
3170 }
3171 }
3172
3173 public function ping( &$rtt = null ) {
3174 // Avoid hitting the server if it was hit recently
3175 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3176 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
3177 $rtt = $this->mRTTEstimate;
3178 return true; // don't care about $rtt
3179 }
3180 }
3181
3182 // This will reconnect if possible or return false if not
3183 $this->clearFlag( DBO_TRX, self::REMEMBER_PRIOR );
3184 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3185 $this->restoreFlags( self::RESTORE_PRIOR );
3186
3187 if ( $ok ) {
3188 $rtt = $this->mRTTEstimate;
3189 }
3190
3191 return $ok;
3192 }
3193
3194 /**
3195 * @return bool
3196 */
3197 protected function reconnect() {
3198 $this->closeConnection();
3199 $this->mOpened = false;
3200 $this->mConn = false;
3201 try {
3202 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3203 $this->lastPing = microtime( true );
3204 $ok = true;
3205 } catch ( DBConnectionError $e ) {
3206 $ok = false;
3207 }
3208
3209 return $ok;
3210 }
3211
3212 public function getSessionLagStatus() {
3213 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3214 }
3215
3216 /**
3217 * Get the replica DB lag when the current transaction started
3218 *
3219 * This is useful when transactions might use snapshot isolation
3220 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3221 * is this lag plus transaction duration. If they don't, it is still
3222 * safe to be pessimistic. This returns null if there is no transaction.
3223 *
3224 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3225 * @since 1.27
3226 */
3227 public function getTransactionLagStatus() {
3228 return $this->mTrxLevel
3229 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3230 : null;
3231 }
3232
3233 /**
3234 * Get a replica DB lag estimate for this server
3235 *
3236 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3237 * @since 1.27
3238 */
3239 public function getApproximateLagStatus() {
3240 return [
3241 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3242 'since' => microtime( true )
3243 ];
3244 }
3245
3246 /**
3247 * Merge the result of getSessionLagStatus() for several DBs
3248 * using the most pessimistic values to estimate the lag of
3249 * any data derived from them in combination
3250 *
3251 * This is information is useful for caching modules
3252 *
3253 * @see WANObjectCache::set()
3254 * @see WANObjectCache::getWithSetCallback()
3255 *
3256 * @param IDatabase $db1
3257 * @param IDatabase ...
3258 * @return array Map of values:
3259 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3260 * - since: oldest UNIX timestamp of any of the DB lag estimates
3261 * - pending: whether any of the DBs have uncommitted changes
3262 * @since 1.27
3263 */
3264 public static function getCacheSetOptions( IDatabase $db1 ) {
3265 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3266 foreach ( func_get_args() as $db ) {
3267 /** @var IDatabase $db */
3268 $status = $db->getSessionLagStatus();
3269 if ( $status['lag'] === false ) {
3270 $res['lag'] = false;
3271 } elseif ( $res['lag'] !== false ) {
3272 $res['lag'] = max( $res['lag'], $status['lag'] );
3273 }
3274 $res['since'] = min( $res['since'], $status['since'] );
3275 $res['pending'] = $res['pending'] ?: $db->writesPending();
3276 }
3277
3278 return $res;
3279 }
3280
3281 public function getLag() {
3282 return 0;
3283 }
3284
3285 function maxListLen() {
3286 return 0;
3287 }
3288
3289 public function encodeBlob( $b ) {
3290 return $b;
3291 }
3292
3293 public function decodeBlob( $b ) {
3294 if ( $b instanceof Blob ) {
3295 $b = $b->fetch();
3296 }
3297 return $b;
3298 }
3299
3300 public function setSessionOptions( array $options ) {
3301 }
3302
3303 /**
3304 * Read and execute SQL commands from a file.
3305 *
3306 * Returns true on success, error string or exception on failure (depending
3307 * on object's error ignore settings).
3308 *
3309 * @param string $filename File name to open
3310 * @param bool|callable $lineCallback Optional function called before reading each line
3311 * @param bool|callable $resultCallback Optional function called for each MySQL result
3312 * @param bool|string $fname Calling function name or false if name should be
3313 * generated dynamically using $filename
3314 * @param bool|callable $inputCallback Optional function called for each
3315 * complete line sent
3316 * @return bool|string
3317 * @throws Exception
3318 */
3319 public function sourceFile(
3320 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3321 ) {
3322 MediaWiki\suppressWarnings();
3323 $fp = fopen( $filename, 'r' );
3324 MediaWiki\restoreWarnings();
3325
3326 if ( false === $fp ) {
3327 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3328 }
3329
3330 if ( !$fname ) {
3331 $fname = __METHOD__ . "( $filename )";
3332 }
3333
3334 try {
3335 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3336 } catch ( Exception $e ) {
3337 fclose( $fp );
3338 throw $e;
3339 }
3340
3341 fclose( $fp );
3342
3343 return $error;
3344 }
3345
3346 public function setSchemaVars( $vars ) {
3347 $this->mSchemaVars = $vars;
3348 }
3349
3350 /**
3351 * Read and execute commands from an open file handle.
3352 *
3353 * Returns true on success, error string or exception on failure (depending
3354 * on object's error ignore settings).
3355 *
3356 * @param resource $fp File handle
3357 * @param bool|callable $lineCallback Optional function called before reading each query
3358 * @param bool|callable $resultCallback Optional function called for each MySQL result
3359 * @param string $fname Calling function name
3360 * @param bool|callable $inputCallback Optional function called for each complete query sent
3361 * @return bool|string
3362 */
3363 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3364 $fname = __METHOD__, $inputCallback = false
3365 ) {
3366 $cmd = '';
3367
3368 while ( !feof( $fp ) ) {
3369 if ( $lineCallback ) {
3370 call_user_func( $lineCallback );
3371 }
3372
3373 $line = trim( fgets( $fp ) );
3374
3375 if ( $line == '' ) {
3376 continue;
3377 }
3378
3379 if ( '-' == $line[0] && '-' == $line[1] ) {
3380 continue;
3381 }
3382
3383 if ( $cmd != '' ) {
3384 $cmd .= ' ';
3385 }
3386
3387 $done = $this->streamStatementEnd( $cmd, $line );
3388
3389 $cmd .= "$line\n";
3390
3391 if ( $done || feof( $fp ) ) {
3392 $cmd = $this->replaceVars( $cmd );
3393
3394 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3395 $res = $this->query( $cmd, $fname );
3396
3397 if ( $resultCallback ) {
3398 call_user_func( $resultCallback, $res, $this );
3399 }
3400
3401 if ( false === $res ) {
3402 $err = $this->lastError();
3403
3404 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3405 }
3406 }
3407 $cmd = '';
3408 }
3409 }
3410
3411 return true;
3412 }
3413
3414 /**
3415 * Called by sourceStream() to check if we've reached a statement end
3416 *
3417 * @param string $sql SQL assembled so far
3418 * @param string $newLine New line about to be added to $sql
3419 * @return bool Whether $newLine contains end of the statement
3420 */
3421 public function streamStatementEnd( &$sql, &$newLine ) {
3422 if ( $this->delimiter ) {
3423 $prev = $newLine;
3424 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3425 if ( $newLine != $prev ) {
3426 return true;
3427 }
3428 }
3429
3430 return false;
3431 }
3432
3433 /**
3434 * Database independent variable replacement. Replaces a set of variables
3435 * in an SQL statement with their contents as given by $this->getSchemaVars().
3436 *
3437 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3438 *
3439 * - '{$var}' should be used for text and is passed through the database's
3440 * addQuotes method.
3441 * - `{$var}` should be used for identifiers (e.g. table and database names).
3442 * It is passed through the database's addIdentifierQuotes method which
3443 * can be overridden if the database uses something other than backticks.
3444 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3445 * database's tableName method.
3446 * - / *i* / passes the name that follows through the database's indexName method.
3447 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3448 * its use should be avoided. In 1.24 and older, string encoding was applied.
3449 *
3450 * @param string $ins SQL statement to replace variables in
3451 * @return string The new SQL statement with variables replaced
3452 */
3453 protected function replaceVars( $ins ) {
3454 $vars = $this->getSchemaVars();
3455 return preg_replace_callback(
3456 '!
3457 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3458 \'\{\$ (\w+) }\' | # 3. addQuotes
3459 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3460 /\*\$ (\w+) \*/ # 5. leave unencoded
3461 !x',
3462 function ( $m ) use ( $vars ) {
3463 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3464 // check for both nonexistent keys *and* the empty string.
3465 if ( isset( $m[1] ) && $m[1] !== '' ) {
3466 if ( $m[1] === 'i' ) {
3467 return $this->indexName( $m[2] );
3468 } else {
3469 return $this->tableName( $m[2] );
3470 }
3471 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3472 return $this->addQuotes( $vars[$m[3]] );
3473 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3474 return $this->addIdentifierQuotes( $vars[$m[4]] );
3475 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3476 return $vars[$m[5]];
3477 } else {
3478 return $m[0];
3479 }
3480 },
3481 $ins
3482 );
3483 }
3484
3485 /**
3486 * Get schema variables. If none have been set via setSchemaVars(), then
3487 * use some defaults from the current object.
3488 *
3489 * @return array
3490 */
3491 protected function getSchemaVars() {
3492 if ( $this->mSchemaVars ) {
3493 return $this->mSchemaVars;
3494 } else {
3495 return $this->getDefaultSchemaVars();
3496 }
3497 }
3498
3499 /**
3500 * Get schema variables to use if none have been set via setSchemaVars().
3501 *
3502 * Override this in derived classes to provide variables for tables.sql
3503 * and SQL patch files.
3504 *
3505 * @return array
3506 */
3507 protected function getDefaultSchemaVars() {
3508 return [];
3509 }
3510
3511 public function lockIsFree( $lockName, $method ) {
3512 return true;
3513 }
3514
3515 public function lock( $lockName, $method, $timeout = 5 ) {
3516 $this->mNamedLocksHeld[$lockName] = 1;
3517
3518 return true;
3519 }
3520
3521 public function unlock( $lockName, $method ) {
3522 unset( $this->mNamedLocksHeld[$lockName] );
3523
3524 return true;
3525 }
3526
3527 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3528 if ( $this->writesOrCallbacksPending() ) {
3529 // This only flushes transactions to clear snapshots, not to write data
3530 throw new DBUnexpectedError(
3531 $this,
3532 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3533 );
3534 }
3535
3536 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3537 return null;
3538 }
3539
3540 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3541 if ( $this->trxLevel() ) {
3542 // There is a good chance an exception was thrown, causing any early return
3543 // from the caller. Let any error handler get a chance to issue rollback().
3544 // If there isn't one, let the error bubble up and trigger server-side rollback.
3545 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3546 $this->unlock( $lockKey, $fname );
3547 } );
3548 } else {
3549 $this->unlock( $lockKey, $fname );
3550 }
3551 } );
3552
3553 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
3554
3555 return $unlocker;
3556 }
3557
3558 public function namedLocksEnqueue() {
3559 return false;
3560 }
3561
3562 /**
3563 * Lock specific tables
3564 *
3565 * @param array $read Array of tables to lock for read access
3566 * @param array $write Array of tables to lock for write access
3567 * @param string $method Name of caller
3568 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3569 * @return bool
3570 */
3571 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3572 return true;
3573 }
3574
3575 /**
3576 * Unlock specific tables
3577 *
3578 * @param string $method The caller
3579 * @return bool
3580 */
3581 public function unlockTables( $method ) {
3582 return true;
3583 }
3584
3585 /**
3586 * Delete a table
3587 * @param string $tableName
3588 * @param string $fName
3589 * @return bool|ResultWrapper
3590 * @since 1.18
3591 */
3592 public function dropTable( $tableName, $fName = __METHOD__ ) {
3593 if ( !$this->tableExists( $tableName, $fName ) ) {
3594 return false;
3595 }
3596 $sql = "DROP TABLE " . $this->tableName( $tableName );
3597 if ( $this->cascadingDeletes() ) {
3598 $sql .= " CASCADE";
3599 }
3600
3601 return $this->query( $sql, $fName );
3602 }
3603
3604 /**
3605 * Get search engine class. All subclasses of this need to implement this
3606 * if they wish to use searching.
3607 *
3608 * @return string
3609 */
3610 public function getSearchEngine() {
3611 return 'SearchEngineDummy';
3612 }
3613
3614 public function getInfinity() {
3615 return 'infinity';
3616 }
3617
3618 public function encodeExpiry( $expiry ) {
3619 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3620 ? $this->getInfinity()
3621 : $this->timestamp( $expiry );
3622 }
3623
3624 public function decodeExpiry( $expiry, $format = TS_MW ) {
3625 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3626 ? 'infinity'
3627 : wfTimestamp( $format, $expiry );
3628 }
3629
3630 public function setBigSelects( $value = true ) {
3631 // no-op
3632 }
3633
3634 public function isReadOnly() {
3635 return ( $this->getReadOnlyReason() !== false );
3636 }
3637
3638 /**
3639 * @return string|bool Reason this DB is read-only or false if it is not
3640 */
3641 protected function getReadOnlyReason() {
3642 $reason = $this->getLBInfo( 'readOnlyReason' );
3643
3644 return is_string( $reason ) ? $reason : false;
3645 }
3646
3647 /**
3648 * @since 1.19
3649 * @return string
3650 */
3651 public function __toString() {
3652 return (string)$this->mConn;
3653 }
3654
3655 /**
3656 * Run a few simple sanity checks
3657 */
3658 public function __destruct() {
3659 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3660 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3661 }
3662 $danglingCallbacks = array_merge(
3663 $this->mTrxIdleCallbacks,
3664 $this->mTrxPreCommitCallbacks,
3665 $this->mTrxEndCallbacks
3666 );
3667 if ( $danglingCallbacks ) {
3668 $callers = [];
3669 foreach ( $danglingCallbacks as $callbackInfo ) {
3670 $callers[] = $callbackInfo[1];
3671 }
3672 $callers = implode( ', ', $callers );
3673 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3674 }
3675 }
3676 }
3677
3678 /**
3679 * @since 1.27
3680 */
3681 abstract class Database extends DatabaseBase {
3682 // B/C until nothing type hints for DatabaseBase
3683 // @TODO: finish renaming DatabaseBase => Database
3684 }